package com.quectel.cms.controller.grid;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.controller.grid.helper.GridHelper;
import com.quectel.cms.util.SessionHolder;
import com.quectel.constant.OrderCodePrefixConstants;
import com.quectel.constant.core.grid.GridConstant;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.core.module.grid.dto.GridEventRecordDto;
import com.quectel.core.module.grid.dto.GridEventRecordHandleDto;
import com.quectel.core.module.grid.dto.GridEventRecordLogDto;
import com.quectel.core.module.grid.dto.GridRegionInfoDto;
import com.quectel.core.module.grid.service.GridEventRecordService;
import com.quectel.core.module.grid.service.GridService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.DateUtils;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import com.quectel.util.kit.OrderUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/02/03 16:42
 */
@RestController
@RequestMapping("gridEventRecord")
@Tag(name = "GridEventRecordController", description = "网格事件相关api")
public class GridEventRecordController extends BaseController {

    @DubboReference
    private GridEventRecordService gridEventRecordService;
    @DubboReference
    private VillageService villageService;
    @DubboReference
    private GridService gridService;

    @Autowired
    private GridHelper gridHelper;


    /**
     * 事件流转
     *
     * @param gridEventRecordHandleDto
     * @return
     */
    @PostMapping("handle")
    @RequirePermissions(values = "gridEventRecord:edit")
    @Operation(summary = "处理网格事件")
    public Response<Object> handle(@RequestBody @Validated GridEventRecordHandleDto gridEventRecordHandleDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(gridEventRecordHandleDto.getGridEventRecordId()));
        if (gridEventRecordService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        GridEventRecordDto dbDto = gridEventRecordService.selectById(gridEventRecordHandleDto.getGridEventRecordId());

        List<GridRegionInfoDto> gridRegionInfoDtos = gridHelper.queryRegionInfoByGroupId(SessionHolder.getSysUser().getGroupId());
        //如果没有地区信息 当前层级不可以操作
        if (CollectionUtils.isEmpty(gridRegionInfoDtos)) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        switch (Objects.requireNonNull(GridConstant.GridEventRecordHandleType.getType(gridEventRecordHandleDto.getHandleStatus()))) {
            //申请办结
            case APPLY_FINISH:
                //必须是待处理或者驳回状态才可以申请办结
                if (!GridConstant.GridEventRecordStatus.TO_BE_PROCESSED.getStatus().equals(dbDto.getStatus())
                        && !GridConstant.GridEventRecordStatus.REJECTED.getStatus().equals(dbDto.getStatus())) {
                    return Response.error("待处理事件才可以申请办结");
                }
                //当前时间是否逾期
                if (dbDto.getDeadline().before(DateTime.now())) {
                    return Response.error("逾期事件无法操作");
                }

                if (!gridRegionInfoDtos.get(0).getLevel().equals(GridConstant.RegionLevel.DISTRICT_LEVEL.getLevel())
                        && !gridRegionInfoDtos.get(0).getLevel().equals(GridConstant.RegionLevel.STREET_LEVEL.getLevel())
                        && !gridRegionInfoDtos.get(0).getLevel().equals(GridConstant.RegionLevel.VILLAGE_LEVEL.getLevel())
                ) {
                    return Response.error("没有上层管理员无法申请办结");
                }

                //修改状态
                dbDto.setStatus(GridConstant.GridEventRecordStatus.TO_BE_FINISHED.getStatus());

                //设置日志
                dbDto.setLogList(Collections.singletonList(
                        packLog(GridConstant.GridEventRecordLogType.FEEDBACK.getStatus()
                                , gridRegionInfoDtos.get(0).getLevel()
                                , gridRegionInfoDtos.get(0).getCode()
                                , "由\"" + gridRegionInfoDtos.get(0).getName() + "\"申请办结"
                                , gridEventRecordHandleDto.getDetail()
                                , gridEventRecordHandleDto.getPicturesJson()
                        ))
                );

                GridRegionInfoDto regionInfoDto = gridHelper.shiftRegionLevel(dbDto, -1);
                if (regionInfoDto != null) {
                    dbDto.setCurrentLevel(regionInfoDto.getLevel());
                    dbDto.setCurrentCode(regionInfoDto.getCode());
                } else {
                    return Response.error("获取上一级地区信息错误");
                }

                gridEventRecordService.saveOrUpdateWithLog(dbDto);

                break;
            case REPORT:
                //必须是待处理状态或者上级处理中才可以上报
                if (!GridConstant.GridEventRecordStatus.TO_BE_PROCESSED.getStatus().equals(dbDto.getStatus())) {
                    return Response.error("待处理事件才可以上报");
                }

                GridRegionInfoDto targetRegion = null;
                //社区或者街道才可以上报
                if (GridConstant.RegionLevel.VILLAGE_LEVEL.getLevel().equals(gridRegionInfoDtos.get(0).getLevel())
                ) {
                    Optional<GridRegionInfoDto> village = gridRegionInfoDtos.stream().filter(gridRegionInfoDto -> gridRegionInfoDto.getCode().equals(String.valueOf(dbDto.getVillageId()))).findFirst();
                    if (!village.isPresent()) {
                        return Response.error("没有该小区信息");
                    }
                    targetRegion = village.get();
                    //赋值街道code
                    dbDto.setStreetCode(village.get().getParentCode());

                } else if (GridConstant.RegionLevel.STREET_LEVEL.getLevel().equals(gridRegionInfoDtos.get(0).getLevel())) {
                    targetRegion = gridRegionInfoDtos.get(0);
                    //赋值区code
                    dbDto.setDistrictCode(gridRegionInfoDtos.get(0).getParentCode());
                } else {
                    return Response.error("社区或者街道才可以上报事件");
                }

                dbDto.setLogList(Collections.singletonList(
                        packLog(GridConstant.GridEventRecordLogType.REPORT.getStatus()
                                , targetRegion.getLevel()
                                , targetRegion.getCode()
                                , "由\"" + targetRegion.getName() + "\"上报\"" + targetRegion.getParentName() + "\""
                                , gridEventRecordHandleDto.getDetail()
                                , gridEventRecordHandleDto.getPicturesJson()
                        ))
                );

                GridRegionInfoDto parentRegionInfo = gridHelper.shiftRegionLevel(dbDto, -1);
                if (parentRegionInfo != null) {
                    dbDto.setCurrentCode(parentRegionInfo.getCode());
                    dbDto.setCurrentLevel(parentRegionInfo.getLevel());
                } else {
                    return Response.error("获取上一级地区信息错误");
                }

                gridEventRecordService.saveOrUpdateWithLog(dbDto);
                break;
            case FINISHED:
                //待办结状态或者处理中才可以办结
                if (!GridConstant.GridEventRecordStatus.TO_BE_FINISHED.getStatus().equals(dbDto.getStatus())
                        && !GridConstant.GridEventRecordStatus.TO_BE_PROCESSED.getStatus().equals(dbDto.getStatus())
                ) {
                    return Response.error("待办结或者上级处理中状态事件才可以办结");
                }
                //查看当前事件最高层级 如果当前等级不是最高层级 则不可以办结
                Byte aByte = gridHelper.queryGridEventSuperLevel(dbDto);
                if (!aByte.equals(gridRegionInfoDtos.get(0).getLevel())) {
                    return Response.error("当前层级不可以办结");
                }

                //修改状态
                dbDto.setStatus(GridConstant.GridEventRecordStatus.FINISHED.getStatus());
                dbDto.setFinishTime(DateTime.now());

                //生成日志
                dbDto.setLogList(Collections.singletonList(
                        packLog(GridConstant.GridEventRecordLogType.FINISH.getStatus()
                                , gridRegionInfoDtos.get(0).getLevel()
                                , gridRegionInfoDtos.get(0).getCode()
                                , "由\"" + gridRegionInfoDtos.get(0).getName() + "\"办结"
                                , gridEventRecordHandleDto.getDetail()
                                , gridEventRecordHandleDto.getPicturesJson()
                        ))
                );

                gridEventRecordService.saveOrUpdateWithLog(dbDto);
                break;
            case REJECTED:
                //待办结状态才可以驳回
                if (!GridConstant.GridEventRecordStatus.TO_BE_FINISHED.getStatus().equals(dbDto.getStatus())) {
                    return Response.error("待办结状态事件才可以驳回");
                }

                //修改状态
                dbDto.setDeadline(gridEventRecordHandleDto.getNewDeadline());
                dbDto.setStatus(GridConstant.GridEventRecordStatus.REJECTED.getStatus());

                //生成日志
                dbDto.setLogList(Collections.singletonList(
                        packLog(GridConstant.GridEventRecordLogType.REJECT.getStatus()
                                , gridRegionInfoDtos.get(0).getLevel()
                                , gridRegionInfoDtos.get(0).getCode()
                                , "由\"" + gridRegionInfoDtos.get(0).getName() + "\"驳回，新的逾期时间：" + DateUtils.format(dbDto.getDeadline(), DateUtils.FormatType.COMMON)
                                , gridEventRecordHandleDto.getDetail()
                                , gridEventRecordHandleDto.getPicturesJson()
                        ))
                );

                GridRegionInfoDto shiftRegionInfoDto = gridHelper.shiftRegionLevel(dbDto, 1);
                if (shiftRegionInfoDto != null) {
                    dbDto.setCurrentLevel(shiftRegionInfoDto.getLevel());
                    dbDto.setCurrentCode(shiftRegionInfoDto.getCode());
                } else {
                    return Response.error("获取下一级地区信息错误");
                }

                gridEventRecordService.saveOrUpdateWithLog(dbDto);
                break;
            default:
                return Response.error("当前操作非法");
        }

        return Response.ok();
    }

    /**
     * 填充日志基本信息
     *
     * @param handleStatus
     * @param regionLevel
     * @param regionCode
     * @param handleDesc
     * @param detail
     * @param picturesJson
     * @return
     */

    private GridEventRecordLogDto packLog(Byte handleStatus, Byte regionLevel, String regionCode, String handleDesc, String detail, String picturesJson) {
        GridEventRecordLogDto dto = new GridEventRecordLogDto();
        dto.setHandleStatus(handleStatus);
        dto.setHandleLevel(regionLevel);
        dto.setHandleUnitName(regionCode);
        dto.setHandleUserType(GridConstant.GridEventRecordPersonType.SYS_USER.getType());
        dto.setHandleUserId(SessionHolder.getSysUserId());
        dto.setHandleDesc(handleDesc);
        dto.setHandleDetail(detail);
        dto.setHandlePicturesJson(picturesJson);
        dto.setCreateTime(DateTime.now());
        return dto;

    }

    /**
     * 网格上报事件
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("gridReportList")
    @RequirePermissions(values = "gridEventRecord:list")
    @Operation(summary = "网格上报事件分页列表")
    public Response<Page<GridEventRecordDto>> gridReportList(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize,
            @Parameter(description = "小区Id") @RequestParam(required = false) Long villageId,
            @Parameter(description = "网格Id") @RequestParam(required = false) Long gridId
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());

        Map<String, Object> gridReportParams = gridHelper.getGridReportParams(request.getParams());
        if (MapUtils.isEmpty(gridReportParams)) {
            Page<GridEventRecordDto> page = new Page<>(request.getPageNo(), request.getPageSize(), 0, Collections.emptyList());
            return Response.<Page<GridEventRecordDto>>ok().wrap(page);
        }

        if (villageId != null) {
            gridReportParams.put(LambdaUtil.getFieldName(GridEventRecordDto::getVillageId), villageId);
        }
        if (gridId != null) {
            gridReportParams.put(LambdaUtil.getFieldName(GridEventRecordDto::getGridId), gridId);
        }

        int total = gridEventRecordService.queryTotal(gridReportParams);

        List<GridEventRecordDto> list = null;
        if (total > 0) {
            list = gridEventRecordService.queryList(gridReportParams);
        } else {
            list = new ArrayList<>();
        }

        Page<GridEventRecordDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<GridEventRecordDto>>ok().wrap(page);
    }

    /**
     * 上级派送事件
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("assignList")
    @RequirePermissions(values = "gridEventRecord:list")
    @Operation(summary = "上级派送事件分页列表")
    public Response<Page<GridEventRecordDto>> c(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());

        Map<String, Object> gridAssignParams = gridHelper.getGridAssignParams(request.getParams());
        if (MapUtils.isEmpty(gridAssignParams)) {
            Page<GridEventRecordDto> page = new Page<>(request.getPageNo(), request.getPageSize(), 0, Collections.emptyList());
            return Response.<Page<GridEventRecordDto>>ok().wrap(page);
        }


        int total = gridEventRecordService.queryTotal(gridAssignParams);

        List<GridEventRecordDto> list = null;
        if (total > 0) {
            list = gridEventRecordService.queryList(gridAssignParams);
        } else {
            list = new ArrayList<>();
        }

        Page<GridEventRecordDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<GridEventRecordDto>>ok().wrap(page);
    }


    /**
     * 本级创建列表
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = "gridEventRecord:list")
    @Operation(summary = "本级创建网格事件列表")
    public Response<Page<GridEventRecordDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());

        Map<String, Object> sysCreatedParams = gridHelper.getSysCreatedParams(request.getParams());
        if (MapUtils.isEmpty(sysCreatedParams)) {
            Page<GridEventRecordDto> page = new Page<>(request.getPageNo(), request.getPageSize(), 0, Collections.emptyList());
            return Response.<Page<GridEventRecordDto>>ok().wrap(page);
        }

        int total = gridEventRecordService.queryTotal(sysCreatedParams);

        List<GridEventRecordDto> list = null;
        if (total > 0) {
            list = gridEventRecordService.queryList(sysCreatedParams);
        } else {
            list = new ArrayList<>();
        }

        Page<GridEventRecordDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<GridEventRecordDto>>ok().wrap(page);
    }

    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "gridEventRecord:edit")
    @Operation(summary = "查询单条网格事件记录")
    public Response<GridEventRecordDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (gridEventRecordService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        GridEventRecordDto gridEventRecordDto = gridEventRecordService.selectById(id);

        return Response.<GridEventRecordDto>ok().wrap(gridEventRecordDto);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "gridEventRecord:info")
    @Operation(summary = "查询单条网格事件记录")
    public Response<GridEventRecordDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (gridEventRecordService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        GridEventRecordDto gridEventRecordDto = gridEventRecordService.selectById(id);

        return Response.<GridEventRecordDto>ok().wrap(gridEventRecordDto);
    }

    /**
     * 保存
     *
     * @param gridEventRecordDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = "gridEventRecord:edit")
    @Operation(summary = "保存单条网格事件记录")
    public Response<Object> save(@RequestBody @Validated GridEventRecordDto gridEventRecordDto) {

        //填充基础数据
        fillSaveCommonData(gridEventRecordDto);
        List<GridRegionInfoDto> localRegionList = gridHelper.queryRegionInfoByGroupId(SessionHolder.getSysUser().getGroupId());

        if (CollectionUtils.isEmpty(localRegionList)) {
            return Response.error("当前用户组没有对应的网格");
        }

        if (GridConstant.RegionLevel.VILLAGE_LEVEL.getLevel().equals(localRegionList.get(0).getLevel()) && gridEventRecordDto.getVillageId() == null) {
            return Response.error("需指定小区");
        }

        if (SystemConstants.NO.equals(gridEventRecordDto.getIfAssign())) {
            //自行处置办结需要填写信息
            if (StringUtils.isEmpty(gridEventRecordDto.getSelfHandleResult()) || StringUtils.isEmpty(gridEventRecordDto.getSelfHandlePicturesJson())) {
                return Response.error("需要填写自行处置情况");
            }
        }


        GridRegionInfoDto createRegionInfo = null;
        //如果是小区级别 需要指定创建的小区和网格
        if (GridConstant.RegionLevel.VILLAGE_LEVEL.getLevel().equals(localRegionList.get(0).getLevel())) {
            VillageDto villageDto = villageService.selectById(gridEventRecordDto.getVillageId());
            createRegionInfo = GridRegionInfoDto.builder()
                    .level(GridConstant.RegionLevel.VILLAGE_LEVEL.getLevel())
                    .code(String.valueOf(villageDto.getId()))
                    .name(villageDto.getName())
                    .parentCode(villageDto.getStreetCode())
                    .parentName(villageDto.getStreetName())
                    .build();
        } else {
            createRegionInfo = localRegionList.get(0);
        }

        if (GridConstant.RegionLevel.DISTRICT_LEVEL.getLevel().equals(createRegionInfo.getLevel())) {
            gridEventRecordDto.setDistrictCode(createRegionInfo.getCode());
        } else if (GridConstant.RegionLevel.STREET_LEVEL.getLevel().equals(createRegionInfo.getLevel())) {
            gridEventRecordDto.setStreetCode(createRegionInfo.getCode());
        } else if (GridConstant.RegionLevel.VILLAGE_LEVEL.getLevel().equals(createRegionInfo.getLevel())) {
            gridEventRecordDto.setVillageId(Long.valueOf(createRegionInfo.getCode()));
        }

        List<GridEventRecordLogDto> logs = new ArrayList<>();

        logs.add(
                packLog(GridConstant.GridEventRecordLogType.CREATE.getStatus()
                        , createRegionInfo.getLevel()
                        , createRegionInfo.getCode()
                        , "由\"" + createRegionInfo.getName() + "\"创建"
                        , null
                        , null
                )
        );

        if (SystemConstants.YES.equals(gridEventRecordDto.getIfAssign())) {
            //查询下属单位 判断绑定关系是否存在于关系列表中
            List<GridRegionInfoDto> childRegionList = gridHelper.queryChildRegionInfoByGroupId(SessionHolder.getSysUser().getGroupId());
            if (CollectionUtils.isEmpty(childRegionList)) {
                return Response.error("没有下级网格，无法指派");
            }

            Set<String> collect = childRegionList.stream().map(GridRegionInfoDto::getCode).filter(Objects::nonNull).collect(Collectors.toSet());
            if (!collect.contains(gridEventRecordDto.getAssignUnit().getCode())) {
                return Response.error("无法指派到指定单位");
            }

            //对不同等级的字段填充
            if (GridConstant.RegionLevel.STREET_LEVEL.getLevel().equals(gridEventRecordDto.getAssignUnit().getLevel())) {
                gridEventRecordDto.setStreetCode(gridEventRecordDto.getAssignUnit().getCode());
            } else if (GridConstant.RegionLevel.VILLAGE_LEVEL.getLevel().equals(gridEventRecordDto.getAssignUnit().getLevel())) {
                gridEventRecordDto.setVillageId(Long.valueOf(gridEventRecordDto.getAssignUnit().getCode()));
            } else if (GridConstant.RegionLevel.GRID_LEVEL.getLevel().equals(gridEventRecordDto.getAssignUnit().getLevel())) {
                gridEventRecordDto.setGridId(Long.valueOf(gridEventRecordDto.getAssignUnit().getCode()));
            }
            //当前所在节点
            gridEventRecordDto.setCurrentLevel(gridEventRecordDto.getAssignUnit().getLevel());
            gridEventRecordDto.setCurrentCode(gridEventRecordDto.getAssignUnit().getCode());

            gridEventRecordDto.setStatus(GridConstant.GridEventRecordStatus.TO_BE_PROCESSED.getStatus());

            logs.add(
                    packLog(GridConstant.GridEventRecordLogType.ASSIGNMENT.getStatus()
                            , createRegionInfo.getLevel()
                            , createRegionInfo.getCode()
                            , "由\"" + createRegionInfo.getName() + "\"指派到\"" + gridEventRecordDto.getAssignUnit().getName() + "\""
                            , gridEventRecordDto.getSelfHandleResult()
                            , gridEventRecordDto.getSelfHandlePicturesJson()
                    )
            );


        } else {
            //当前所在节点
            gridEventRecordDto.setCurrentLevel(createRegionInfo.getLevel());
            gridEventRecordDto.setCurrentCode(createRegionInfo.getCode());
            //未指派则是办结状态
            gridEventRecordDto.setStatus(GridConstant.GridEventRecordStatus.FINISHED.getStatus());
            gridEventRecordDto.setFinishTime(DateTime.now());

            logs.add(
                    packLog(GridConstant.GridEventRecordLogType.FINISH.getStatus()
                            , createRegionInfo.getLevel()
                            , createRegionInfo.getCode()
                            , "由\"" + createRegionInfo.getName() + "\"自行处置办结"
                            , gridEventRecordDto.getSelfHandleResult()
                            , gridEventRecordDto.getSelfHandlePicturesJson()
                    )
            );
        }
        //事件来源
        gridEventRecordDto.setSourceType(GridConstant.GridEventRecordSourceType.BACKGROUND_CREATION.getType());
        //事件编号
        gridEventRecordDto.setEventNo(OrderUtils.getOrderNo(OrderCodePrefixConstants.GRID_EVENT_RECORD_PREFIX));
        //创建层级信息
        gridEventRecordDto.setCreatorLevel(createRegionInfo.getLevel());
        gridEventRecordDto.setCreatorUniqueFlag(createRegionInfo.getCode());
        gridEventRecordDto.setCreateTime(DateTime.now());
        gridEventRecordDto.setLogList(logs);
        gridEventRecordService.saveOrUpdateWithLog(gridEventRecordDto);

        return Response.ok();
    }


    /**
     * 修改
     *
     * @param gridEventRecordDto
     * @return
     */
    @PostMapping("update")
    @RequirePermissions(values = "gridEventRecord:edit")
    @Operation(summary = "修改单条网格事件记录")
    public Response<Object> update(@RequestBody @Validated GridEventRecordDto gridEventRecordDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(gridEventRecordDto.getId()));
        if (gridEventRecordService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(gridEventRecordDto);

        gridEventRecordService.updateById(gridEventRecordDto);

        return Response.ok();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "gridEventRecord:delete")
    @Operation(summary = "批量删除存在的网格事件记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (gridEventRecordService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        gridEventRecordService.deleteBatch(ids);

        return Response.ok();
    }
}
